// pages/main/application/application.js
Page({
  data: {
    applications: [],
    businessApps: [],
    administrativeApps: [],
    operationsApps: [],
    configurationApps: [],
    visualizationApps: [],
    filteredBusinessApps: [],
    filteredAdministrativeApps: [],
    filteredOperationsApps: [],
    filteredConfigurationApps: [],
    filteredVisualizationApps: [],
    filteredApps: [],
    searchKeyword: '',
    loading: true,
    userInfo: {},
    currentCategory: 'all', // 当前选中的分类
    scrollLeft: 0 // 分类标签滚动位置
  },

  onLoad() {
    this.loadUserInfo();
    this.loadApplications();
  },

  onShow() {
    this.loadApplications();
  },

  // 加载用户信息
  loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('user_info');
      if (userInfo) {
        this.setData({
          userInfo: userInfo
        });
      }
    } catch (e) {
      console.error('获取用户信息失败:', e);
    }
  },
  onShareAppMessage() {
  },
  // 加载应用列表
  loadApplications() {
    const username = wx.getStorageSync('username');
    if (!username) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetUserApplications/`,
      method: 'POST',
      data: {
        username: username
      },
      success: (res) => {
        if (res.data.status) {
          const apps = res.data.applications || [];
          // 按应用类型分类
          const businessApps = apps.filter(app => app.app_type === 'business' || app.app_type === undefined || app.app_type === null);
          const administrativeApps = apps.filter(app => app.app_type === 'administrative');
          const operationsApps = apps.filter(app => app.app_type === 'operations');
          const configurationApps = apps.filter(app => app.app_type === 'configuration');
          const visualizationApps = apps.filter(app => app.app_type === 'visualization');
          console.log('应用分类结果:', {
            total: apps.length,
            business: businessApps.length,
            administrative: administrativeApps.length,
            operations: operationsApps.length,
            configuration: configurationApps.length,
            visualization: visualizationApps.length
          });
          this.setData({
            applications: apps,
            businessApps: businessApps,
            administrativeApps: administrativeApps,
            operationsApps: operationsApps,
            configurationApps: configurationApps,
            visualizationApps: visualizationApps,
            filteredApps: apps,
            loading: false
          });
          // 根据当前分类和搜索关键词更新显示
          this.updateFilteredApps();
        } else {
          wx.showToast({
            title: res.data.message || '获取应用列表失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('获取应用列表失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // Lin UI 搜索框 - 输入时触发
  onSearchChange(e) {
    const keyword = (e.detail.value || '').trim();
    this.setData({ searchKeyword: keyword });
    this.filterApplications(keyword);
  },

  // Lin UI 搜索框 - 确认搜索时触发
  onSearchConfirm(e) {
    const keyword = (e.detail.value || '').trim();
    this.setData({ searchKeyword: keyword });
    this.filterApplications(keyword);
    console.log('搜索确认:', keyword);
  },

  // Lin UI 搜索框 - 清除搜索时触发
  onSearchClear() {
    this.setData({ 
      searchKeyword: ''
    });
    this.updateFilteredApps();
    console.log('清除搜索');
  },

  // Lin UI 搜索框 - 点击搜索按钮时触发，跳转到全局搜索页面
  onSearchButtonTap() {
    const keyword = this.data.searchKeyword || '';
    wx.navigateTo({
      url: `/pages/main/global-search/global-search?keyword=${encodeURIComponent(keyword)}`
    });
  },

  // 分类切换
  onCategoryChange(e) {
    const category = e.currentTarget.dataset.category;
    const index = e.currentTarget.dataset.index;
    
    this.setData({
      currentCategory: category
    });
    
    // 滚动到中间位置
    this.scrollToCenter(index);
    
    // 刷新该类别的数据
    this.loadApplications();
  },

  // 滚动标签到中间位置
  scrollToCenter(index) {
    const query = wx.createSelectorQuery().in(this);
    query.select('.category-container').boundingClientRect();
    query.selectAll('.category-tag').boundingClientRect();
    query.exec((res) => {
      if (res && res[0] && res[1] && res[1].length > 0) {
        const containerWidth = res[0].width; // 容器宽度
        const tags = res[1]; // 所有标签的位置信息
        
        if (tags[index]) {
          // 计算标签在滚动内容中的绝对位置（从内容开始到标签左边缘的距离）
          // 第一个标签的左边距是30rpx，后续每个标签左边距也是30rpx
          let tagAbsoluteLeft = 30; // 第一个标签的左边距
          for (let i = 0; i < index; i++) {
            tagAbsoluteLeft += tags[i].width + 30; // 加上标签宽度和间距
          }
          
          // 标签中心在滚动内容中的绝对位置
          const tagCenterAbsolute = tagAbsoluteLeft + tags[index].width / 2;
          
          // 计算需要滚动的距离：使标签中心对齐容器中心
          const scrollLeft = tagCenterAbsolute - containerWidth / 2;
          
          this.setData({
            scrollLeft: Math.max(0, scrollLeft)
          });
        }
      }
    });
  },

  // 更新过滤后的应用
  updateFilteredApps() {
    const { currentCategory, businessApps, administrativeApps, operationsApps, configurationApps, visualizationApps, searchKeyword, applications } = this.data;
    
    // 如果有搜索关键词，先过滤所有应用
    let filteredBusinessApps = businessApps;
    let filteredAdministrativeApps = administrativeApps;
    let filteredOperationsApps = operationsApps;
    let filteredConfigurationApps = configurationApps;
    let filteredVisualizationApps = visualizationApps;
    
    if (searchKeyword) {
      const lowerKeyword = searchKeyword.toLowerCase();
      const filterFn = (app) => {
        const name = (app.name || '').toLowerCase();
        return name.includes(lowerKeyword);
      };
      
      filteredBusinessApps = businessApps.filter(filterFn);
      filteredAdministrativeApps = administrativeApps.filter(filterFn);
      filteredOperationsApps = operationsApps.filter(filterFn);
      filteredConfigurationApps = configurationApps.filter(filterFn);
      filteredVisualizationApps = visualizationApps.filter(filterFn);
    }
    
    // 更新过滤后的应用数组
    this.setData({
      filteredBusinessApps: filteredBusinessApps,
      filteredAdministrativeApps: filteredAdministrativeApps,
      filteredOperationsApps: filteredOperationsApps,
      filteredConfigurationApps: filteredConfigurationApps,
      filteredVisualizationApps: filteredVisualizationApps
    });
  },

  // 过滤应用
  filterApplications(keyword) {
    this.setData({ searchKeyword: keyword });
    this.updateFilteredApps();
  },

  // 点击应用
  onAppTap(e) {
    const app = e.currentTarget.dataset.app;
    console.log('点击应用:', app);

    if (app.url) {
      this.navigateWithConfiguredUrl(app);
    } else {
      this.navigateToCategory(app);
    }
  },

  navigateWithConfiguredUrl(app) {
    let targetUrl = (app.url || '').trim();
    if (!targetUrl) {
      wx.showToast({
        title: '未配置跳转地址',
        icon: 'none'
      });
      return;
    }

    if (targetUrl.startsWith('http')) {
      wx.showToast({
        title: '暂不支持打开外部链接',
        icon: 'none'
      });
      return;
    }

    if (!targetUrl.startsWith('/')) {
      targetUrl = `/${targetUrl}`;
    }

    const connector = targetUrl.includes('?') ? '&' : '?';
    const url = `${targetUrl}${connector}id=${app.id}&name=${encodeURIComponent(app.name)}`;

    wx.navigateTo({
      url,
      fail: () => {
        wx.showToast({
          title: '跳转失败，请检查链接',
          icon: 'none'
        });
      }
    });
  },
  navigateToCategory(app) {
    wx.navigateTo({
      url: `/pages/main/app-category/app-category?appId=${app.id}&appName=${encodeURIComponent(app.name)}&color=${app.color}&description=${encodeURIComponent(app.description || '')}`
    });
  },
});